from django.db import models
from django.contrib.auth.models import User
from django.shortcuts import get_list_or_404

# Create your models here.

class CompetitorGroup(models.Model):
    
    score = models.IntegerField(default=0)



class CUser(models.Model):
    user = models.OneToOneField(User)
    user_img = models.ImageField(upload_to="Userhead",default="0000")
    group = models.ForeignKey(CompetitorGroup,default=None)

    def __str__(self):
        return self.user.username

    def get_right_question_ids(self):
        return [id.question_id for id in self.log_set.all()]
    
    def if_right_question(self,id):
        if id in self.get_right_question_ids():
            return True
        else:
            return False

class Skills(models.Model):
    name = models.CharField(max_length=200)
    cuser = models.ForeignKey(CUser)
    

class Question(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(default="There is no content ...")
    files =  models.FileField(upload_to="Files")
    answer = models.CharField(max_length=200)
    link = models.CharField(max_length=300,default=None)

    def get_describle(self):
        if len(self.content) > 40:
            return self.content[:40] +"..."
        else:
            return self.content

    def get_tags(self):
        return self.tags_set.all()

    @staticmethod
    def get_by_tag(tag):
        if tag == "all":return [tag.question for tag in get_list_or_404(Tags)]
        tags =  get_list_or_404(Tags,content=tag)            
        return [tag.question for tag in tags]

    def if_right(self,an):
        if self.answer  == an:
            return True
        return False

class Tags(models.Model):
    content = models.CharField(max_length=100)
    question = models.ForeignKey(Question)

    @staticmethod
    def get_all_tags():
        tags = [ tag.content for tag in  get_list_or_404(Tags)]
        return set(tags)



class Log(models.Model):
    user = models.ForeignKey(CUser)
    question_id = models.IntegerField(default=0)



    @staticmethod
    def if_exist(cuser,ques_id):
        if cuser.log_set.filter(question_id=ques_id) :
            return True
        return False





